<template>
    <div style="width: 500px;">
    <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="原密码" prop="oldPassword">
            <el-input type="password" v-model="form.oldPassword" maxlength="20"></el-input>
        </el-form-item>
        <el-form-item label="新密码" prop="newPassword">
            <el-input type="password" v-model="form.newPassword" maxlength="20"></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
            <el-input type="password" v-model="form.confirmPassword" maxlength="20"></el-input>
        </el-form-item>
        <el-form-item>
            <el-button type="primary" @click="submitForm">修改</el-button>
            <el-button>取消</el-button>
        </el-form-item>
    </el-form>
    </div>
</template>
<script>
    import {changePassword} from "@/api/person/changePassword";
    export default {
        name: 'ChangePwd',
        data() {
            return {
                form: {},
                rules: {
                    oldPassword: [
                        {required: true, message: "旧密码不能为空", trigger: "blur"}
                    ],
                    newPassword: [
                        {required: true, message: "新密码不能为空", trigger: "blur"}
                    ],
                    confirmPassword: [
                        {required: true, message: "确认密码不能为空", trigger: "blur"},
                        {required: true, validator: this.equalToPassword, trigger: "blur"}
                    ]
                },
            }
        },
        created() {
            this.reset()
        },
        methods: {
            equalToPassword(rule, value, callback) {
                if (value !== this.form.newPassword) {
                    callback(new Error('两次输入密码不一致!'));
                } else {
                    callback();
                }
            },
            submitForm() {
                this.$refs["form"].validate(valid => {
                    if(valid) {
                        changePassword(this.form).then(resp=>{
                            if(resp.code == 200) {
                                this.$message({message:'操作成功', type:'success'})
                            }
                            this.reset()
                        }).catch((e)=>{
                            this.$alert(e.msg, '错误', {type:'error'})
                            this.reset()
                        })
                    }
                })
            },
            reset() {
                this.form = {
                    oldPassword: '',
                    newPassword: '',
                    confirmPassword: ''
                }
            }
        }
    }
</script>
